#!/usr/bin/env bash
# mindbender shell
# Usage: mindbender [-OPTION] COMMAND [ARG]...
# 
# Global OPTION is one of:
#   -v      increase verbosity
#   -q      suppress all messages
#   -t      force logging to non-ttys
#           (default is to log messages to stderr only when it's a tty)
#
# Generated: 2015-02-09
set -eu

if [ -z "${MINDBENDER_HOME:-}" ]; then
    export MINDBENDER_COMMAND=${POJANG_ORIGINAL_COMMAND:-$0}
    unset POJANG_ORIGINAL_COMMAND
    if [ x"$MINDBENDER_COMMAND" = x"$(type -p "mindbender" 2>/dev/null)" ]; then
        # no need to expand command when it's on PATH
        MINDBENDER_COMMAND=mindbender
    else
        # resolve relative path (but no need to follow symlinks)
        MINDBENDER_COMMAND="$(cd "$(dirname "$MINDBENDER_COMMAND")"; pwd)/$(basename "$MINDBENDER_COMMAND")"
    fi
    export USAGE_TOOL_COMMAND=mindbender  USAGE_TOOL_PATH=$MINDBENDER_COMMAND
    Self=$(readlink -f "$0" 2>/dev/null || {
        # XXX readlink -f is only available in GNU coreutils
        cd $(dirname -- "$0")
        n=$(basename -- "$0")
        if [ -L "$n" ]; then
            L=$(readlink "$n")
            if [ x"$L" != x"${L#/}" ]; then
                echo "$L"; exit
            else
                cd "$(dirname -- "$L")"
                n=$(basename -- "$L")
            fi
        fi
        echo "$(pwd -P)/$n"
    })
    Here=$(dirname "$Self")

    # Keep a backup of some environment variables
    for v in PATH NODE_PATH
    do  vbak=MINDBENDER_ORIG_$v
          declare -p $v    &>/dev/null || continue
        ! declare -p $vbak &>/dev/null || continue
        export "$vbak=${!v}"
    done

    # Setup environment
    unset CDPATH
    export MINDBENDER_HOME=${Here%/bin}
    #  dependencies
    PATH="$MINDBENDER_HOME/depends/bundled/.all/bin:$PATH"
    PATH="$MINDBENDER_HOME/depends/runtime/.all/bin:$PATH"
    #  node_modules
    export NODE_PATH="$MINDBENDER_HOME/node_modules${NODE_PATH:+:$NODE_PATH}"
    PATH="$MINDBENDER_HOME/node_modules/.bin:$PATH"
    #  shell runtime scripts
    PATH="$MINDBENDER_HOME/bin/mindbender.d:$PATH"
    export PATH

    # for msg logging
    export SHLVL=0 MINDBENDER_LOGLVL=${MINDBENDER_LOGLVL:-1}
    # export MINDBENDER_LOG_TO_NONTTY=
fi

# make sure everything we need is available
"$MINDBENDER_HOME"/depends/check-runtime-depends-once


# Process options
while getopts "vtq" opt; do
    case $opt in
        v)
            let ++MINDBENDER_LOGLVL
            ;;
        q)
            MINDBENDER_LOGLVL=0
            ;;
        t)
            export MINDBENDER_LOG_TO_NONTTY=true
            ;;
    esac
done
shift $(($OPTIND - 1))


# Process input arguments
[ $# -gt 0 ] || {
    usage "$0" "No COMMAND given" || true
    # enumerate available COMMANDs discoverable from PATH
    echo
    echo "# Available COMMANDs are:"
    IFS=:
    tmp=$(mktemp -d "${TMPDIR:-/tmp}"/mindbender-usage.XXXXXXX)
    trap 'rm -rf "$tmp"' EXIT
    for path in $PATH; do
        for exe in "$path"/mindbender-*; do
            [ -x "$exe" ] || continue
            usage "$exe" | head -1 | sed -n '/ -- / s/.* -- //p' >>"$tmp"/desc
            cmd=${exe##*/mindbender-}
            echo "mindbender $cmd  #"
        done
    done | column -t >"$tmp"/commands
    paste "$tmp"/commands "$tmp"/desc
    false
}
Cmd=$1; shift


# Check if it's a valid command
exe=mindbender-"$Cmd"
if type "$exe" &>/dev/null; then
    set -- "$exe" "$@"
else
    usage "$0" "$Cmd: invalid COMMAND"
fi


# Run given command under this environment
exec "$@"
